package com.jjty.dataGenerator.jshjy.utils;

import cn.hutool.core.util.IdUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jjty.dataGenerator.jserji.entity.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;

@Component
public class PushHttpClient {

//    @Autowired
//    private SignUtils signUtil;
    //@Autowired
    //private RestTemplate restTemplate;

    // 配置参数（建议放在application.yml中）
    @Value("${jsedu.api.base-url}") // 接口基础地址，如：https://api.jsedu.com
    private String baseUrl;
    @Value("${jsedu.app-secret}") // 接入密钥（平台提供）
    private String appSecret;

    private final RestTemplate restTemplate;

    public PushHttpClient(ObjectMapper objectMapper) {
        this.restTemplate = new RestTemplate();

        // 使用配置好的 ObjectMapper
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(objectMapper);
        restTemplate.getMessageConverters().add(converter);
    }

    /**
     * 通用推送方法
     * @param apiPath 接口路径（如：/openapi/stu-card/sync/heartbeat）
     * @param requestBody 请求体对象
     * @return 接口响应
     */
    public ApiResponse push(String apiPath, Object requestBody) {
        try {
            // 1. 生成请求头参数
            String nonce = IdUtil.fastUUID();
            String timestamp = String.valueOf(System.currentTimeMillis());
            String bodyJson = JsonUtils.toJsonString(requestBody);
            String sign = SignUtils.generateSignature(bodyJson, nonce, timestamp, appSecret);
            System.out.println("请求体：" + bodyJson);
            System.out.println("请求头：" + "X-Nonce=" + nonce + ", X-Timestamp=" + timestamp + ", X-App-Secret=" + appSecret + ", X-Sign=" + sign);
            boolean isSignValid = SignUtils.verifySignature(bodyJson, nonce, timestamp, appSecret, sign);
            System.out.println("签名验证结果：" + isSignValid);


            // 2. 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("X-Nonce", nonce);
            headers.set("X-Timestamp", timestamp);
            headers.set("X-App-Secret", appSecret);
            headers.set("X-Sign", sign);

            // 3. 发送POST请求
            HttpEntity<String> requestEntity = new HttpEntity<>(bodyJson, headers);
            ResponseEntity<ApiResponse> response = restTemplate.postForEntity(
                    baseUrl + apiPath,
                    requestEntity,
                    ApiResponse.class
            );

            // 4. 处理响应
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                ApiResponse errorResp = new ApiResponse();
                errorResp.setCode(-1);
                errorResp.setMsg("HTTP请求失败，状态码：" + response.getStatusCodeValue());
                return errorResp;
            }
        } catch (Exception e) {
            ApiResponse errorResp = new ApiResponse();
            errorResp.setCode(-2);
            errorResp.setMsg("推送异常：" + e.getMessage());
            return errorResp;
        }
    }
}